package org.zhangkun.jmsg.core.network;

import java.util.ArrayList;

import org.zhangkun.jmsg.bean.DataUnPack;
import org.zhangkun.jmsg.bean.SendMsgInfo;

/**
 * 
 * Copyright (C), 2006-2010, ChengDu Lovo info. Co., Ltd. FileName:
 * MsgTransport.java
 * 
 * 信息传输
 * 
 * @author zhangkun
 * @Date 2011-7-10
 * @version 1.00
 */

public class MsgTransport extends Thread {

	public final static MsgTransport instance = new MsgTransport();

	/**
	 * 消息传输队列
	 */
	private ArrayList<SendMsgInfo> allWaitSendMsg = new ArrayList<SendMsgInfo>();

	private boolean stop;

	private MsgTransport() {
		setName("MsgTransport Thread");
	}

	public void acceptRecvMsg(DataUnPack dup) {
		SendMsgInfo sendMsgInfo = findMsg(dup.getMsg());

		if (sendMsgInfo != null) {
			if (sendMsgInfo.getListener() != null) {
				invoikingListener(sendMsgInfo, true);
				allWaitSendMsg.remove(sendMsgInfo);
			}
		}
	}

	public void addMsg(SendMsgInfo sendMsgInfo) {
		// TODO Auto-generated method stub
		allWaitSendMsg.add(sendMsgInfo);
	}

	private SendMsgInfo findMsg(String id) {
		for (SendMsgInfo sendMsgInfo : allWaitSendMsg) {
			if (sendMsgInfo.getDp().getDataID().equals(id))
				return sendMsgInfo;
		}
		return null;
	}

	private void invoikingListener(SendMsgInfo sendMsgInfo, boolean flag) {
		sendMsgInfo.getListener().acceptRecvMsg(sendMsgInfo, flag);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (!stop) {
			if (allWaitSendMsg.size() > 0) {
				SendMsgInfo sendMsgInfo = allWaitSendMsg.get(0);
				long currTime = System.currentTimeMillis();
				if (sendMsgInfo.getLastSendTime() == 0
						|| currTime - sendMsgInfo.getLastSendTime() > 1000) {
					sendMsgInfo.setLastSendTime(currTime);
					if (sendMsgInfo.isRepeat()) {
						NetConnection.instance.sendBroadcast(sendMsgInfo
								.getDp());
						if (sendMsgInfo.getSendNum() >= sendMsgInfo
								.getRepeatNum()) {
							if (sendMsgInfo.getListener() != null)
								invoikingListener(sendMsgInfo, false);
							allWaitSendMsg.remove(sendMsgInfo);
						}
						sendMsgInfo.setSendNum(sendMsgInfo.getSendNum() + 1);
					} else {
						if (sendMsgInfo.getLastSendTime() == 0) {
							NetConnection.instance.sendBroadcast(sendMsgInfo
									.getDp());
							sendMsgInfo.setLastSendTime(currTime);
						} else {
							if (sendMsgInfo.getListener() != null)
								invoikingListener(sendMsgInfo, false);
							allWaitSendMsg.remove(sendMsgInfo);
						}
					}
				}
			}
			try {
				if (gcTime >= 600) {
					gcTime = 0;
					System.gc();
				} else
					gcTime++;
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private int gcTime = 0;
}
